<template>
  <div>
    <el-button type="primary" @click="openDialog()">新增隐患上报</el-button>
    <el-table :data="tableData" style="width: 100%; margin-top: 16px">
      <el-table-column type="index" :index="(index) => index + 1" label="编号" width="80" />
    
      <el-table-column prop="stName" label="安全隐患" />
      <el-table-column prop="state" label="状态" :formatter="formatStatus" />
      <el-table-column prop="amName" label="管理员" />
      <el-table-column prop="createTime" label="上报时间" :formatter="formatDateTime" />
      <el-table-column prop="dealTime" label="解决时间" :formatter="formatDateTime" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="openDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 16px"
      background
      layout="prev, pager, next, jumper, ->, total"
      :total="total"
      :page-size="pageSize"
      :current-page="currentPage"
      @current-change="handlePageChange"
    />
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="60%" top="5vh">
      <el-form :model="form" label-width="120px" class="safety-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="安全隐患">
              <el-select 
                v-model="form.sid" 
                placeholder="请选择安全隐患类型" 
                @change="handleSafetyTypeChange" 
                clearable 
                :disabled="safetyTypesLoading"
                style="width: 100%"
                class="custom-select"
              >
                <el-option v-for="type in safetyTypes" :key="type.sid" :label="`${type.stName}`" :value="type.sid" />
              </el-select>
              <div v-if="safetyTypesLoading" class="el-loading-text">加载中...</div>
              <div v-if="safetyTypesError" class="text-danger">{{ safetyTypesError }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-select v-model="form.state" placeholder="请选择状态" style="width: 100%">
                <el-option label="未处理" :value="1"></el-option>
                <el-option label="已处理" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="管理员">
              <el-select 
                v-model="form.amId" 
                placeholder="请选择管理员" 
                @change="handleAdminChange" 
                clearable 
                :disabled="administratorsLoading"
                style="width: 100%"
                class="custom-select"
              >
                <el-option v-for="admin in administrators" :key="admin.amId" :label="`${admin.amName} `" :value="admin.amId" />
              </el-select>
              <div v-if="administratorsLoading" class="el-loading-text">加载中...</div>
              <div v-if="administratorsError" class="text-danger">{{ administratorsError }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上报时间">
              <el-date-picker
                v-model="form.createTime"
                type="datetime"
                placeholder="选择上报时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DDTHH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="解决时间">
              <el-date-picker
                v-model="form.dealTime"
                type="datetime"
                placeholder="选择解决时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DDTHH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessageBox } from 'element-plus';
import { postRequest, putRequest, deleteRequest ,getRequest} from '@/utils/request';

const tableData = ref([]);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
const dialogVisible = ref(false);
const dialogTitle = ref('新增隐患上报');
const form = reactive({
  id: null,
  sid: '',
  stName: '',
  state: '',
  amId: '',
  amName: '',
  createTime: '',
  dealTime: ''
});
const safetyTypes = ref([]);
const administrators = ref([]);
const safetyTypesLoading = ref(false);
const administratorsLoading = ref(false);
const safetyTypesError = ref('');
const administratorsError = ref('');

const formatStatus = (row, column, value) => {
  const statusMap = { 1: '未处理', 2: '已处理' };
  return statusMap[value] || value;
};

const formatDateTime = (row, column, value) => {
  if (!value) return '';
  // 将ISO时间格式转换为'YYYY-MM-DD HH:mm:ss'格式
  const date = new Date(value);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
};

function fetchSafetyTypes() {
  safetyTypesLoading.value = true;
  safetyTypesError.value = '';
  getRequest('/securityThreat/getSecurityThreatList').then(res => {
    if (res && res.data && Array.isArray(res.data.data)) {
      const validTypes = res.data.data
        .filter(element => element && element.id !== undefined)
        .map(element => ({
          sid: String(element.id),
          stName: element.stName || element.name || `隐患类型${element.id}`
        }));
      safetyTypes.value = validTypes;
      if (validTypes.length === 0) {
        safetyTypesError.value = '未找到安全隐患类型数据，请联系系统管理员';
      }
    } else {
      safetyTypesError.value = '安全隐患类型数据格式不正确';
      console.error('安全隐患类型数据格式错误:', res);
    }
  }).catch(error => {
    safetyTypesError.value = '获取安全隐患类型失败: ' + (error.message || '网络错误');
    console.error('获取安全隐患类型失败:', error);
  }).finally(() => {
    safetyTypesLoading.value = false;
  });
}

function fetchAdministrators() {
  administratorsLoading.value = true;
  administratorsError.value = '';
  getRequest('/areaManager/getAreaManagerList').then(res => {
    if (res && res.data && Array.isArray(res.data.data)) {
      const validAdmins = res.data.data
        .filter(element => element && element.id !== undefined)
        .map(element => ({
          amId: String(element.id),
          amName: element.amName || element.username || element.name || `管理员${element.id}`
        }));
      administrators.value = validAdmins;
      if (validAdmins.length === 0) {
        administratorsError.value = '未找到管理员数据，请联系系统管理员';
      }
    } else {
      administratorsError.value = '管理员数据格式不正确';
      console.error('管理员数据格式错误:', res);
    }
  }).catch(error => {
    administratorsError.value = '获取管理员列表失败: ' + (error.message || '网络错误');
    console.error('获取管理员列表失败:', error);
  }).finally(() => {
    administratorsLoading.value = false;
  });
}

function fetchData() {
  postRequest('/reportSafetyHazards/getReportSafetyHazardsByPage', { current: currentPage.value, size: pageSize.value }).then(res => {
    if (res && res.data) {
      tableData.value = Array.isArray(res.data.data.reportSafetyHazards) ? res.data.data.reportSafetyHazards : [];
      total.value = res.data.total || 0;
    } else {
      tableData.value = [];
      total.value = 0;
    }
  });
}

function openDialog(row) {
  if (row) {
    dialogTitle.value = '编辑隐患上报';
    Object.assign(form, row);
    // 确保ID为字符串类型，与下拉选项值类型一致
    form.sid = String(row.sid || '');
    form.amId = String(row.amId || row.amName || '');
    // 设置日期时间字段
    form.createTime = row.createTime || '';
    form.dealTime = row.dealTime || '';
    // 等待数据加载完成后再触发选择事件
    setTimeout(() => {
      handleSafetyTypeChange(form.sid);
      handleAdminChange(form.amId);
    }, 0);
  } else {
    dialogTitle.value = '新增隐患上报';
    form.id = null;
    form.sid = '';
    form.stName = '';
    form.state = '';
    form.amId = '';
    form.amName = '';
  }
  dialogVisible.value = true;
}

function handleSafetyTypeChange(sid) {
  const selectedType = safetyTypes.value.find(type => type.sid === String(sid));
  if (selectedType) {
    form.stName = selectedType.stName;
  } else {
    form.stName = '';
    console.warn('未找到ID为', sid, '的安全隐患类型');
  }
}

function handleAdminChange(amId) {
  const selectedAdmin = administrators.value.find(admin => admin.amId === String(amId));
  if (selectedAdmin) {
    form.amName = selectedAdmin.amName;
  } else {
    form.amName = '';
    console.warn('未找到ID为', amId, '的管理员');
  }
}

function handleSubmit() {
  if (form.id) {
    putRequest('/reportSafetyHazards/updateReportSafetyHazardsById', form).then(() => {
      dialogVisible.value = false;
      fetchData();
    });
  } else {
    postRequest('/reportSafetyHazards/addReportSafetyHazards', form).then(() => {
      dialogVisible.value = false;
      fetchData();
    });
  }
}

function handleDelete(id) {
  ElMessageBox.confirm('确定要删除该记录吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteRequest(`/reportSafetyHazards/deleteReportSafetyHazardsById/${id}`).then(() => {
      fetchData();
    });
  }).catch(() => {});
}

function handlePageChange(page) {
  currentPage.value = page;
  fetchData();
}

onMounted(() => {
  fetchData();
  fetchSafetyTypes();
  fetchAdministrators();
});
</script>

<style scoped>
.safety-form {
  padding: 20px 0;
}

.custom-select {
  width: 100%;
}

.custom-select :deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.custom-select :deep(.el-input__wrapper:hover) {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.custom-select :deep(.el-select-dropdown) {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.el-loading-text {
  color: #909399;
  font-size: 12px;
  margin-top: 4px;
}

.text-danger {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 4px;
}

:deep(.el-dialog) {
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
  padding: 20px 24px;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #ebeef5;
  padding: 16px 24px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #303133;
}

:deep(.el-input__wrapper),
:deep(.el-textarea__inner) {
  border-radius: 8px;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover),
:deep(.el-textarea__inner:hover) {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.el-input__wrapper:focus-within),
:deep(.el-textarea__inner:focus) {
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}
</style>